package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.UserLike;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FriendService;
import com.itheima.service.mongo.UserLikeService;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.UserLikeCountVo;
import com.itheima.vo.UserLikeVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserLikeManager {
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private UserLikeService userLikeService;

    @Reference
    private FriendService friendService;

    @Reference
    private UserInfoService userInfoService;

    //喜欢
    public void saveUserLike(Long likeUserId) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 保存喜欢关系
        userLikeService.save(userId, likeUserId);

        //3.判断二人是否互相喜欢
        boolean isMutualLike = userLikeService.isMutualLike(userId, likeUserId);
        if (isMutualLike) {
            //3-1 向mongo中保存好友关系
            friendService.save(userId, likeUserId);

            //3-2 向环信中保存好友关系
            huanXinTemplate.addContacts(userId, likeUserId);
        }
    }

    //不喜欢
    public void deleteUserLike(Long likeUserId) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 删除mongo中的好友关系
        friendService.delete(userId, likeUserId);

        //3. 删除环信中的好友关系
        huanXinTemplate.deleteContacts(userId, likeUserId);

        //4. 删除喜欢表中的关系
        userLikeService.delete(userId, likeUserId);
    }

    //统计用户的喜欢 朋友 粉丝数量
    public UserLikeCountVo findUserCounts() {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 调用service统计数量
        return userLikeService.findUserCounts(userId);
    }

    //查询用户列表
    public PageBeanVo findUserList(Integer type, Integer pageNum, Integer pageSize) {
        //1. 获取登录用户id
        Long userId = UserHolder.get().getId();

        //2. 调用service查询
        PageBeanVo pageBeanVo = userLikeService.findUserList(userId,type,pageNum,pageSize);
        List<UserLikeVo> userLikeVoList = (List<UserLikeVo>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(userLikeVoList)){
            for (UserLikeVo userLikeVo : userLikeVoList) {
                UserInfo userInfo = userInfoService.findByUserId(userLikeVo.getId());
                BeanUtil.copyProperties(userInfo,userLikeVo);
            }
        }

        return pageBeanVo;
    }
}
